//
//  TouchDetectingWindow.m
//  TouchDetectingWebView
//
//  Created by Kishikawa Katsumi on 10/05/05.
//  Copyright 2010 Kishikawa Katsumi. All rights reserved.
//

#import "TouchDetectingWindow.h"

@implementation TouchDetectingWindow

@synthesize viewToObserve;
@synthesize touchDelegate;

- (void)dealloc {
    [super dealloc];
}

- (void)forwardTouchesBegan:(NSNumber *)point {
    if ([touchDelegate respondsToSelector:@selector(gotTouchesBegan:)]) {
        [touchDelegate gotTouchesBegan:[point CGPointValue]];
    }
}

- (void)forwardTouchesMoved:(NSNumber *)point {
    if ([touchDelegate respondsToSelector:@selector(gotTouchesMoved:)]) {
        [touchDelegate gotTouchesMoved:[point CGPointValue]];
    }
}

- (void)forwardTouchesEnded:(NSNumber *)point {
    if ([touchDelegate respondsToSelector:@selector(gotTouchesEnded:)]) {
        [touchDelegate gotTouchesEnded:[point CGPointValue]];
    }
}

// UIWindow が最初にタッチイベントを受け取る
- (void)sendEvent:(UIEvent *)event {
    [super sendEvent:event];
    
    // 対象のビュー、もしくはデリゲートが設定されてなければ何もしない
    if (!viewToObserve || !touchDelegate) {
        return;
    }
    
    // 今回はシングルタップのみ
    NSSet *touches = [event allTouches];
    if (touches.count != 1) {
        return;
    }
    
    // タッチしたビューが監視対象のビューの階層構造に含まれるかどうか
    UITouch *touch = touches.anyObject;
    if (![touch.view isDescendantOfView:viewToObserve]) {
        return;
    }
    
    CGPoint point = [touch locationInView:viewToObserve];
    if (touch.phase == UITouchPhaseBegan) {
        [self performSelector:@selector(forwardTouchesBegan:) 
                   withObject:[NSValue valueWithCGPoint:point] 
                   afterDelay:0.0];
    } else if (touch.phase == UITouchPhaseMoved) {
        [self performSelector:@selector(forwardTouchesMoved:) 
                   withObject:[NSValue valueWithCGPoint:point] 
                   afterDelay:0.0];
    } else if (touch.phase == UITouchPhaseEnded) {
        [self performSelector:@selector(forwardTouchesEnded:) 
                   withObject:[NSValue valueWithCGPoint:point] 
                   afterDelay:0.0];
    }
}

@end
